#!/usr/bin/env python3
"""
Demo script for GCR Solver Manager

This script demonstrates the core functionality of the GCR Solver Manager system.
"""

import asyncio
import sys
from pathlib import Path

# Add src to path and change working directory
import os
src_path = str(Path(__file__).parent / "src")
sys.path.insert(0, src_path)
os.chdir(Path(__file__).parent)

from core.config import Config
from database.session import init_database, get_session
from database.models import BuildConfiguration
from cli.commands import main


async def demo_database():
    """Demonstrate database functionality."""
    print("🗄️  Database Demo")
    print("=" * 50)
    
    # Initialize database
    print("Initializing database...")
    await init_database(drop_existing=True)
    print("✅ Database initialized")
    
    # Create sample build configuration
    print("\nCreating sample build configuration...")
    with get_session() as session:
        config = BuildConfiguration(
            name="cuda-gmres-debug",
            gpu_type="cuda",
            solver_type="gmres",
            debug_mode=True,
            description="CUDA GMRES solver in debug mode"
        )
        session.add(config)
        session.commit()
        print(f"✅ Created config: {config}")
    
    # Query configurations
    print("\nQuerying build configurations...")
    with get_session() as session:
        configs = session.query(BuildConfiguration).all()
        for config in configs:
            print(f"  - {config.name} ({config.gpu_type}/{config.solver_type})")
    
    print()


def demo_config():
    """Demonstrate configuration management."""
    print("⚙️  Configuration Demo")
    print("=" * 50)
    
    # Load configuration
    config = Config.load_from_file()
    print(f"Environment: {config.environment}")
    print(f"Debug mode: {config.debug}")
    print(f"Database URL: {config.database.url}")
    print(f"Build directory: {config.build.build_dir}")
    print(f"Default GPU type: {config.build.default_gpu_type}")
    print()


def demo_cli():
    """Demonstrate CLI functionality."""
    print("🖥️  CLI Demo")
    print("=" * 50)
    print("Available CLI commands:")
    print("  gsm --help                    # Show help")
    print("  gsm db init                   # Initialize database")
    print("  gsm db info                   # Show database info")
    print("  gsm config show               # Show configuration")
    print("  gsm build run --gpu=cuda      # Run build (not implemented yet)")
    print("  gsm test run --solver=gmres   # Run test (not implemented yet)")
    print("  gsm logs list                 # List logs (not implemented yet)")
    print("  gsm status                    # Show system status")
    print()


async def main_demo():
    """Run the complete demo."""
    print("🚀 GCR Solver Manager Demo")
    print("=" * 70)
    print("This demo showcases the core functionality of the GCR Solver Manager")
    print("system for managing builds, tests, and logs of Helmholtz solvers.")
    print()
    
    # Configuration demo
    demo_config()
    
    # Database demo
    await demo_database()
    
    # CLI demo
    demo_cli()
    
    print("🎉 Demo completed!")
    print("\nNext steps:")
    print("1. Install the package: pip install -e .")
    print("2. Initialize database: gsm db init")
    print("3. Check status: gsm status")
    print("4. Explore CLI: gsm --help")


if __name__ == "__main__":
    asyncio.run(main_demo())